<?php
/**
 * Created by PhpStorm.
 * User: 35083
 * Date: 2019/7/9
 * Time: 16:52
 */

namespace app\api\controller;


class Wechatdev
{
    /**
     *
     * 绑定设备
     * http://api.witsleep.com/api/wechatdev/devBind?access_token=oH-8p44cBFeZbLDADriQQEQC8p-8&_hosp=1001&devtype=0&devsn=s1001
     *
     */
    public function devBind()
    {
        $access_token = trim($_REQUEST['access_token']);
        $userModel = new \app\admin\model\User();

        $_hosp = trim($_REQUEST['_hosp']);
        if (empty($_hosp)) {
            $return['err'] = 1;
            $return['msg'] = '参数错误[_hosp]';
            return json($return);
        }
        $userInfo = getUserinfoForAccessToken($access_token, 1, $_hosp);
        if (empty($userInfo)) {
            $userInfo = getUserinfoForAccessToken($access_token, 2, $_hosp);
            if (empty($userInfo)) {
                $return['err'] = 10009;
                $return['msg'] = '未找到相关用户';
                echo json_encode($return, true);
                exit;
            }
        }

        $currDate = getCurrDate();
        $devtype = trim(input("request.devtype"));//设备类型 0睡眠仪 1枕头
        $devsn = trim(input("request.devsn"));//--设备编号
        $devname = trim(input("request.devname"));//--设备名字
        $mac = trim(input("request.mac"));  //--设备mac

        $is_rent = 0;

        //查找是否是租赁设备
        $model = new \app\admin\model\RentDevice();
        $deviceInfo = $model->getDataForWhere(['device_sn' => $devsn, 'is_delete' => 0], "id,device_sn,device_model,rent_price,deposit_price,explain_price,position_id");

        if (!empty($deviceInfo)) {//说明是租用设备
            $is_rent = 1;
            $time24Hour_second = strtotime("-24hours");
            $time24Hour_time = date("Y-m-d H:i:s", $time24Hour_second);
            //是否已经下单
            $payModel = new \app\admin\model\PayOrder();
            $OrderInfo = $payModel->getDataForWhere(['device_sn' => $devsn, 'uid' => $userInfo['id'], 'is_delete' => 0, 'stat' => 1, 'ptime' => array('>=', $time24Hour_time), 'ty' => 2], "*", "id desc");
            if (empty($OrderInfo)) {
                $positionInfo = $this->getRendPosionInfo($deviceInfo['position_id']);
                $deviceInfo['position']="";
                if($positionInfo){
                    $deviceInfo['position']=$positionInfo['name'];
                }
                $return['err'] = 1000;
                $return['msg'] = '需要支付';
                $return['data'] = $deviceInfo;
                return json($return);
            }
        }


        if ($devtype != 0 && $devtype != 1 && $devtype != 88) {
            $return = ['err' => 2, 'msg' => '操作失败,设备类型不正确', 'devMsg' => '操作失败，参数错误[devtype]'];
            return json($return);
        }

        $DevModel = new \app\admin\model\Dev();
        $w = array(
            'uid' => $userInfo['id'],
            'devtype' => $devtype,
            'devname' => $devname,
            'is_delete' => 0,
            'ty' => 1
        );
        $data = array(
            'uid' => $userInfo['id'],
            'devsn' => $devsn,
            'devname' => $devname,
            'devtype' => $devtype,
            'mac' => $mac,
            'ctime' => $currDate['date'],
            'is_delete' => 0,
            'ty' => 1,
            'is_rent' => $is_rent
        );
        $devInfo = $DevModel->getDataForWhere($w);
        if (!empty($devInfo)) {//修改
            $res = $DevModel->updateData($data, $devInfo['id']);
            if ($res || $res == 0) {
                $return['err'] = 0;
                $return['msg'] = '操作成功';
                $return['id'] = $devInfo['id'];
                return json($return);
            } else {
                $return['err'] = 3;
                $return['msg'] = '操作失败';
                return json($return);
            }

        } else//添加
        {
            $insertID = $DevModel->add($data);
            if ($insertID) {
                $return['err'] = 0;
                $return['msg'] = '操作成功';
                $return['id'] = $insertID;
                return json($return);

            } else {
                $return['err'] = 4;
                $return['msg'] = '操作失败';
                return json($return);
            }
        }
    }


    public function getRendPosionInfo($id){
        $model = new \app\admin\model\RentPosition();
        return  $model->getDataForWhere(['id'=>$id]);
    }
    /**
     *
     * 解除绑定设备
     * http://127.0.0.1:9093/api/user/devUnBind
     *
     */
    public function devUnBind()
    {
        $currDate = getCurrDate();
        $access_token = trim($_REQUEST['access_token']);
        $userModel = new \app\admin\model\User();

        $_hosp = trim($_REQUEST['_hosp']);
        if (empty($_hosp)) {
            $return['err'] = 1;
            $return['msg'] = '参数错误[_hosp]';
            return json($return);
        }
        $userInfo = getUserinfoForAccessToken($access_token, 1, $_hosp);
        if (empty($userInfo)) {
            $userInfo = getUserinfoForAccessToken($access_token, 2, $_hosp);
            if (empty($userInfo)) {
                $return['err'] = 10009;
                $return['msg'] = '未找到相关用户';
                echo json_encode($return, true);
                exit;
            }
        }
        $id = trim(input("request.id"));

        if (empty($id)) {
            $return = ['err' => 1, 'msg' => '操作失败', 'devMsg' => '操作失败，参数错误[id]'];
            return json($return);
        }
        $DevModel = new \app\admin\model\Dev();
        $devInfo = $DevModel->getDataForWhere(array('uid' => $userInfo['id'], 'id' => $id, 'is_delete' => 0));
        if (empty($devInfo)) {
            $return = ['err' => 1, 'msg' => '操作失败,设备已经不存在了', 'devMsg' => '操作失败，参数错误[id]'];
            return json($return);
        }
        $update = array('is_delete' => 1, 'delete_time' => $currDate['date']);
        $w = array('uid' => $userInfo['id'], 'id' => $id);

        $res = $DevModel->updateDataForWhere($update, $w);
        if ($res || $res == 0) {
            $return['err'] = 0;
            $return['msg'] = '操作成功';
            return json($return);
        } else {
            $return['err'] = 1;
            $return['msg'] = '操作失败';
            return json($return);
        }
    }

    /**
     *
     * 获取我的设备列表接口
     * http://127.0.0.1:9093/api/user/devUnBind
     *
     */
    public function lists()
    {
        $currDate = getCurrDate();
        $access_token = trim($_REQUEST['access_token']);
        $userModel = new \app\admin\model\User();

        $_hosp = trim($_REQUEST['_hosp']);
        if (empty($_hosp)) {
            $return['err'] = 1;
            $return['msg'] = '参数错误[_hosp]';
            return json($return);
        }
        $userInfo = getUserinfoForAccessToken($access_token, 1, $_hosp);
        if (empty($userInfo)) {
            $userInfo = getUserinfoForAccessToken($access_token, 2, $_hosp);
            if (empty($userInfo)) {
                $return['err'] = 10009;
                $return['msg'] = '未找到相关用户';
                echo json_encode($return, true);
                exit;
            }
        }

        $DevModel = new \app\admin\model\Dev();
        $lists = $DevModel->getDataForWheres(array('uid' => $userInfo['id'], 'is_delete' => 0, 'ty' => 1), "id,uid,devtype,devsn,devname,mac");
        $return['err'] = 0;
        $return['msg'] = '操作成功';
        $return['data'] = $lists;
        return json($return);

    }


    /**
     *
     * 获取我的设备列表接口
     * http://127.0.0.1:9093/api/user/devUnBind
     *
     */
    public function getInfo()
    {

        $id = trim(input("request.id"));//用户auth
        $access_token = trim($_REQUEST['access_token']);
        $userModel = new \app\admin\model\User();

        $_hosp = trim($_REQUEST['_hosp']);
        if (empty($_hosp)) {
            $return['err'] = 1;
            $return['msg'] = '参数错误[_hosp]';
            return json($return);
        }
        $userInfo = getUserinfoForAccessToken($access_token, 1, $_hosp);
        if (empty($userInfo)) {
            $userInfo = getUserinfoForAccessToken($access_token, 2, $_hosp);
            if (empty($userInfo)) {
                $return['err'] = 10009;
                $return['msg'] = '未找到相关用户';
                echo json_encode($return, true);
                exit;
            }
        }

        if (empty($id)) {
            $return = ['err' => 1, 'msg' => '操作失败,参数错误', 'devMsg' => '操作失败，参数错误[id]'];
            return json($return);
        }


        $DevModel = new \app\admin\model\Dev();
        $info = $DevModel->getDataForWhere(array('uid' => $userInfo['id'], 'id' => $id), "id,uid,devtype,devsn,devname,mac,is_delete");

        if (empty($info)) {
            $return = ['err' => 1, 'msg' => '设备不存在', 'devMsg' => '设备不存在'];
            return json($return);
        }

        if ($info['is_delete'] == 1) {
            $return = ['err' => 1, 'msg' => '设备已删除', 'devMsg' => '设备已删除'];
            return json($return);
        }
        $return['err'] = 0;
        $return['msg'] = '成功';
        $return['data'] = $info;
        return json($return);

    }

    /**
     * http://api.witsleep.com/api/wechatdev/autoRemoveDevice
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */

    public function autoRemoveDevice()
    {

        $currDate = getCurrDate();
        $time24Hour_second = strtotime("-24hours");
        $time24Hour_time = date("Y-m-d H:i:s", $time24Hour_second);
        $payModel = new \app\admin\model\PayOrder();
        $lists = $payModel->getDataForWheres(['ptime' => array('<', $time24Hour_time), 'ty' => 2,'is_device_del'=>0], "*", "id asc");
        foreach ($lists as $key => $val) {
            $DevModel = new \app\admin\model\Dev();
            $w = array('uid' => $val['uid'], 'is_rent' => 1, 'devsn' => $val['device_sn']);
            $orderDevInfo = $DevModel->getDataForWhere($w);
            if (!empty($orderDevInfo)) {
                if ($orderDevInfo['is_delete'] == 0) {
                    $update = array('is_delete' => 1, 'delete_time' => $currDate['date']);
                    $DevModel->updateDataForWhere($update, $w);
                }
            }
            $payModel->updateDataForWhere(['is_device_del'=>1,'remove_device_time'=>date("Y-m-d H:i:s")],['id'=>$val['id']]);
        }
    }
}